/// <reference path="jquery-3.2.1.min.js" />
/// <reference path="../../layer/layer/layer.js" />


$(function () {
    $web.init();
});
//var left_right_times;

var $web = {
    arrSkinName: ['index-skin-primary', 'index-skin-cyan', 'index-skin-green', 'index-skin-indigo', 'index-skin-grey', 'index-skin-pink', 'index-skin-purple', 'index-skin-red', 'index-skin-teal', 'index-skin-orange'],
    //设置主题 index:左边皮肤索引，topIndex:顶部皮肤索引
    setTheme: function (index, topIndex) {
        if (!isNaN(parseInt(index))) {
            localStorage.setItem("web-theme-leftmenu", index);
            var webThemeIndex = localStorage.getItem("web-theme-leftmenu");
            if (webThemeIndex == null) {
                index = 0;
            }
            var indexleftmenu = $(".index-left-menu");
            indexleftmenu.removeClass("sidebar-nav1");
            indexleftmenu.removeClass("sidebar-nav");
            if (index == 1) {
                indexleftmenu.addClass("sidebar-nav1");
            }
            else if (index == 0) {
                indexleftmenu.addClass("sidebar-nav");
            }
        }

        if (!isNaN(parseInt(topIndex))) {
            for (var i = 0; i < $web.arrSkinName.length; i++) {
                $(".index-top").removeClass($web.arrSkinName[i]);
            }
            $(".index-top").addClass($web.arrSkinName[topIndex]);
            localStorage.setItem("web-theme-top", topIndex);
        }

    },
    init: function () {
        $('[data-toggle="tooltip"]').tooltip();
        $web.setTheme(localStorage.getItem("web-theme-leftmenu"), localStorage.getItem("web-theme-top"));

        $web.MenuState.toggle(null, localStorage.getItem("menuIsOpen"));

        resize();
        window.onresize = function () {
            resize();
        };
        function resize() {
            var left = $(".index-left");
            var main = $(".index-main");
            var winWidth = document.body.scrollWidth;
            if (winWidth <= 768) {
                if (!left.hasClass("index-left-220")) {
                    left.removeClass("index-left-80").addClass("index-left-220");
                    left.find(".index-left-menu").removeClass("sidebar-nav2");
                    $(".index-tab").removeClass("index-left-range-sm").addClass("index-left-range-lg");
                }
                left.removeClass("index-left-left0").addClass("index-left-left220");
                main.removeClass("index-left-range-lg").removeClass("index-left-range-sm").addClass("index-left-range-sm0");
            } else {
                left.removeClass("index-left-left220");
                if (left.hasClass("index-left-220")) {
                    main.removeClass("index-left-range-sm0").addClass("index-left-range-lg");
                } else {
                    main.removeClass("index-left-range-sm0").addClass("index-left-range-sm");
                }
            }
        }

    },
    //菜单状态 打开收缩
    MenuState: {
        //展开/收起
        toggle: function ($this, isOpen) {
            if (isNaN(parseInt(isOpen)) && $this)
                $this = $($this);
            var left = $(".index-left");
            var leftmenu = $(".index-left-menu");
            var tab = $(".index-tab");
            var main = $(".index-main");
            var winWidth = document.body.scrollWidth;
            if (!isNaN(parseInt(isOpen))) {
                if (isOpen == 2) {
                    if (winWidth > 768) {
                        $web.MenuState.leftW220();
                    }
                }
                else if (isOpen == 1)
                    $web.MenuState.leftW80();
                localStorage.setItem("menuIsOpen", isOpen);
            }

            if (winWidth <= 768) {
                if (left.hasClass("index-left-left220")) {
                    left.removeClass("index-left-80").removeClass("index-left-left220").addClass("index-left-left0");
                    main.removeClass("index-left-range-sm").addClass("index-left-range-lg");
                }
                else {
                    left.removeClass("index-left-left0").addClass("index-left-left220");
                    main.removeClass("index-left-range-lg").addClass("index-left-range-sm0");
                }

            } else {
                if (left.hasClass("index-left-220")) {//判断是不是 220px 的样式
                    if ($this)
                        $web.MenuState.leftW220();
                    else
                        $web.MenuState.leftW80();
                } else {
                    if ($this)
                        $web.MenuState.leftW80();
                    else
                        $web.MenuState.leftW220();
                }
            }

        },
        leftW220: function () {
            var left = $(".index-left");
            var leftmenu = $(".index-left-menu");
            var tab = $(".index-tab");
            var main = $(".index-main");

            tab.removeClass("index-left-range-lg").addClass("index-left-range-sm");
            main.removeClass("index-left-range-lg").addClass("index-left-range-sm");
            left.removeClass("index-left-220").addClass("index-left-80");

            leftmenu.addClass("sidebar-nav2");//添加鼠标移动上去 展开菜单 样式
        },
        leftW80: function () {
            var left = $(".index-left");
            var leftmenu = $(".index-left-menu");
            var tab = $(".index-tab");
            var main = $(".index-main");

            left.removeClass("index-left-80").addClass("index-left-220");
            tab.removeClass("index-left-range-sm").addClass("index-left-range-lg");
            main.removeClass("index-left-range-sm").addClass("index-left-range-lg");

            leftmenu.removeClass("sidebar-nav2");//移除鼠标移动上去 展开菜单 样式
        }
    },
    //全屏
    fullScreen: function () {
        var isFullScreen = false;
        var requestFullScreen = function () {//全屏
            var de = document.documentElement;
            if (de.requestFullscreen) {
                de.requestFullscreen();
            } else if (de.mozRequestFullScreen) {
                de.mozRequestFullScreen();
            } else if (de.webkitRequestFullScreen) {
                de.webkitRequestFullScreen();
            }
            else {
                alert("该浏览器不支持全屏");
            }
        };
        //退出全屏 判断浏览器种类
        var exitFull = function () {
            // 判断各种浏览器，找到正确的方法
            var exitMethod = document.exitFullscreen || //W3C
                document.mozCancelFullScreen ||    //Chrome等
                document.webkitExitFullscreen || //FireFox
                document.webkitExitFullscreen; //IE11
            if (exitMethod) {
                exitMethod.call(document);
            }
            else if (typeof window.ActiveXObject !== "undefined") {//for Internet Explorer
                var wscript = new ActiveXObject("WScript.Shell");
                if (wscript !== null) {
                    wscript.SendKeys("{F11}");
                }
            }
        };

        return {
            handleFullScreen: function ($this) {
                $this = $($this);
                if (isFullScreen) {
                    exitFull();
                    isFullScreen = false;
                    $this.find("i").removeClass("fa fa-compress");
                    $this.find("i").addClass("fa fa-expand");
                    $this.attr("title", "全屏");
                } else {
                    requestFullScreen();
                    isFullScreen = true;
                    $this.find("i").removeClass("fa fa-expand");
                    $this.find("i").addClass("fa fa-compress");
                    $this.attr("title", "退出全屏");
                }
            },
        };

    }(),
    //皮肤
    Skin: {
        window: function () {
            var html = '<!-- Modal -->' +
        '<div class="modal fade" id="index-skin-win" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">' +
          '<div class="modal-dialog" role="document">' +
            '<div class="modal-content">' +
              '<div class="modal-header">' +
                '<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>' +
                '<h4 class="modal-title" id="myModalLabel">皮肤设置</h4>' +
              '</div>' +
              '<div class="modal-body">' +

                '<form>' +
                    '<div class="form-group">' +
                        '<label for="exampleInputEmail1">导航条颜色：</label>' +
                       '<ul class="list-unstyled list-inline" style="text-align: center;">';

            for (var i = 0; i < $web.arrSkinName.length; i++) {
                html += '<li><div class="index-skin ' + $web.arrSkinName[i] + '" onclick="$web.setTheme(null,' + i + ');"></div> </li>';
            }

            html += '</ul>' +
                       '</div>' +
                       '<div class="form-group">' +
                           '<label>菜单皮肤：</label>' +
                           '<select class="form-control" onchange="$web.setTheme($(this).val(),null)">' +
                               '<option value="0">==菜单皮肤==</option>' +
                               '<option value="0">深色</option>' +
                               '<option value="1">浅色</option>' +
                           '</select>' +
                       '</div>' +
                       '<div class="form-group">' +
                           '<label>菜单默认状态：</label>' +
                           '<select class="form-control" onchange="$web.MenuState.toggle(null,$(this).val())">' +
                               '<option value="">==菜单默认状态==</option>' +
                               '<option value="1">收起</option>' +
                               '<option value="2">展开</option>' +
                           '</select>' +
                       '</div>' +

                   '</form>' +

               '</div>' +
               '<div class="modal-footer">' +
                 '<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>' +
                 //'<button type="button" class="btn btn-primary">Save changes</button>' +
               '</div>' +
             '</div>' +
            '</div>' +
            '</div>';
            return html;
        }
    },
    //顶部选项卡 
    Tab: {
        //标签页面点击事件
        click: function ($this) {
            $this = $($this);
            $web.Tab.activePage($this);
        },
        //$this 该对象必须包含属性 mdata-id 、mdata-title、mdata-url
        //<li class="index-tab-li" title="菜单管理"><a><span>菜单管理</span><i class="fa fa-close"></i></a></li>
        Add: function ($this) {
            $this = $($this);
            var dataid = $this.attr("mdata-id");
            var datatitle = $this.attr("mdata-title");
            var dataurl = $this.attr("mdata-url");
            var tabUl = $(".index-tab .index-tab-contabs-scroll ul");
            //循环 ul 里面的 li
            var lis = tabUl.find("li"); var flag = 0;
            lis.removeClass("active");
            for (var i = 0; i < lis.length; i++) {
                var id = $(lis[i]).attr("mdata-id");
                var title = $(lis[i]).attr("mdata-title");
                var url = $(lis[i]).attr("mdata-url");
                if (dataid == id && datatitle == title && dataurl == url) {
                    //存在，执行选中 并定位
                    flag = $(lis[i]);
                    $(lis[i]).addClass("active");
                    break;
                }
            }

            if (flag == 0) {//添加新的标签页到页面中
                flag = '<li class="index-tab-li active" title="' + datatitle + '" mdata-id="' + dataid + '" mdata-title="' + datatitle + '" mdata-url="' + dataurl + '" onclick="$web.Tab.click(this);"><a href="javascript:void(0);"><span>' + datatitle + '</span><i class="fa fa-remove" onclick="$web.Tab.close(event,$(this).parent().parent())"></i></a></li>';
                tabUl.append(flag);
                $web.Tab.CreateIframe(dataurl, dataid);
            } else {
                //$web.Tab.refreshThisTab();
            }

            $web.Tab.locationTab($(flag));//定位导航
            $web.Tab.activePage($(flag), true);
        },
        //关闭选项卡标签
        close: function (event, $this) {
            //阻止事件冒泡
            event.stopPropagation();
            $this = $($this);
            $web.Tab.upOrNextLoad($this, function () {
                //移除
                var dataid = $this.attr("mdata-id");
                var datatitle = $this.attr("mdata-title");
                var dataurl = $this.attr("mdata-url");
                var PageContent = top.$("#PageContent");
                PageContent.find("iframe[mdata-id='" + dataid + "']").remove();
                $this.remove();
            });
        },
        //如果标签页面被关闭，调用该函数 来检查 加载上一个页面还是下一个页面
        upOrNextLoad: function (dom, callback) {
            //判断该关闭的选项卡是否是 选中状态  选中需要对 标签定位做调整
            dom = $(dom);
            if (dom.hasClass("active")) {
                var up = dom.prev();//获取上一个元素
                var next = dom.next();//获取下一个元素
                if (up.length == 1) {
                    $web.Tab.activePage(up);
                } if (next.length == 1) {
                    $web.Tab.activePage(next);
                }
            }
            if (callback) callback(up);
        },
        //页面选中函数 选中并统一请求 页面
        activePage: function (dom, isJump) {
            var dataid = dom.attr("mdata-id");
            var datatitle = dom.attr("mdata-title");
            var dataurl = dom.attr("mdata-url");
            //移除所有的 选中样式
            if (!dom.hasClass("active") || isJump) {
                //请求页面并加载在页面中
                var PageContent = top.$("#PageContent");
                PageContent.find("iframe").removeClass("Main-Iframe-Active");
                var iframe = PageContent.find("iframe[mdata-id='" + dataid + "']");
                iframe.addClass("Main-Iframe-Active");
            }
            if (!dom.hasClass("active")) {
                $(".index-tab .index-tab-contabs-scroll ul li").removeClass("active");
                dom.addClass("active");
            }
        },
        //计算导航 定位
        locationTab: function (dom) {
            var dataid = dom.attr("mdata-id");
            var datatitle = dom.attr("mdata-title");
            var dataurl = dom.attr("mdata-url");
            var lookDiv = $(".index-tab .index-tab-contabs-scroll");//可见区域
            var ul = $(".index-tab .index-tab-contabs-scroll ul");
            var ulW = ul.find("li").length * 120;

            ul.css("width", ulW);
            var lookW = lookDiv.width();
            var lookLeft = lookDiv.offset().left;
            var ulleft = ul.offset().left;

            var thisDomInUlLeft = 0;//当前元素在 ul 中的 偏移量
            var lis = ul.find("li");
            for (var i = 0; i < lis.length; i++) {
                var id = $(lis[i]).attr("mdata-id");
                var title = $(lis[i]).attr("mdata-title");
                var url = $(lis[i]).attr("mdata-url");
                if (dataid == id && datatitle == title && dataurl == url) {
                    thisDomInUlLeft = (i + 1) * 120;
                    break;
                }
            }

            var thisleft = parseInt((ulleft + thisDomInUlLeft));//当前选中的 li 偏移量
            //如果菜单藏入右边 那么向左移动
            if (thisleft >= parseInt(lookLeft + lookW)) {
                ul.animate({ "left": "-=" + parseInt(thisleft - parseInt(lookLeft + lookW)) + "px" }, 50);
            }
            //如果菜单藏入左边 那么向右移动
            if (parseInt(thisleft - 120) < lookLeft) {
                ul.animate({ "left": "+=" + parseInt(lookLeft - thisleft + 120) + "px" }, 50);
            }

        },
        //前移动
        upMove: function () {
            var ul = $(".index-tab .index-tab-contabs-scroll ul");
            var lookDiv = $(".index-tab .index-tab-contabs-scroll");//可见区域
            var lookW = lookDiv.width();
            var lookLeft = lookDiv.offset().left;
            var ulleft = ul.offset().left;
            //找出与左边 250 零界点最近的 一个 li
            ul.find("li").each(function (i, e) {
                var thisleft = ulleft + (i * 120);
                if (thisleft >= parseInt(lookLeft - 120) && thisleft <= lookLeft) {
                    $web.Tab.locationTab($(this));
                    return false;
                }
            });
        },
        //往后移动
        nextMove: function () {
            var ul = $(".index-tab .index-tab-contabs-scroll ul");
            var lookDiv = $(".index-tab .index-tab-contabs-scroll");//可见区域
            var lookW = lookDiv.width();
            var lookLeft = lookDiv.offset().left;
            var ulleft = ul.offset().left;
            //找出与右边 零界点最近的 一个 li
            ul.find("li").each(function (i, e) {
                var thisleft = ulleft + (i * 120);
                thisleft = (thisleft + 120);
                if (thisleft > (lookLeft + lookW) && thisleft <= ((lookLeft + lookW)) + 120) {
                    $web.Tab.locationTab($(this));
                    return false;
                }
            });
        },
        //移除其他选项卡
        removeOtherTab: function () {
            var ul = $(".index-tab .index-tab-contabs-scroll ul");
            var PageContent = top.$("#PageContent");
            var lis = ul.find("li:gt(0)");
            lis.each(function (i, e) {
                if (!$(this).hasClass("active")) {
                    var dataid = $(this).attr("mdata-id");
                    PageContent.find("iframe[mdata-id='" + dataid + "']").remove();
                    return $(this).remove();
                }
            });
            $web.Tab.activePage(ul.find("li.active"), true);
            $web.Tab.locationTab(ul.find("li.active"));
        },
        //移除所有选项卡
        removeAllTab: function () {
            var ul = $(".index-tab .index-tab-contabs-scroll ul");
            var PageContent = top.$("#PageContent");
            ul.find("li:gt(0)").each(function (i, e) {
                var dataid = $(this).attr("mdata-id");
                PageContent.find("iframe[mdata-id='" + dataid + "']").remove();
            });
            ul.find("li:gt(0)").remove();
            var home = ul.find("li:eq(0)");
            $web.Tab.activePage(home, true);
            $web.Tab.locationTab(home);
        },
        //刷新当前选中的选项卡
        refreshThisTab: function (dom) {
            var li = "";
            if (dom) {
                li = $(dom);
                $web.Tab.activePage(li, true);
            }
            else {
                li = $(".index-tab .index-tab-contabs-scroll ul li.active");
                $web.Tab.activePage(li, true);
            }
            var PageContent = $("#PageContent");
            var iframe = PageContent.find("iframe[mdata-id='" + li.attr("mdata-id") + "']");
            var index = top.$web.Loading.start();

            iframe.attr("src", iframe.attr("src")).on("load", function () {
                //关闭loading提示
                top.$web.Loading.end(index);
            });

        },
        //创建 Iframe 
        CreateIframe: function (src, id) {
            var PageContent = top.$("#PageContent");
            PageContent.find("iframe").removeClass("Main-Iframe-Active");
            var iframeName = src.replace("/", "FrameWork_").replace(/\//g, "");
            var html = "<iframe class=\"Main-Iframe Main-Iframe-Active\" frameborder=\"0\" name=\"" + iframeName + "\" src=\"" + src + "\" mdata-id=\"" + id + "\"></iframe>";
            PageContent.append(html);
            var index = top.$web.Loading.start();

            $("iframe:visible").on("load", function () {
                //关闭loading提示
                top.$web.Loading.end(index);
            });

        }
    },
    //pjax 页面请求函数
    Pjax: {
        JumpUrl: function (options) {//pjax
            var defaults = {
                href: "",
                dom: "",
                filter: null,
                callback: null,
                fragment: "body",
            };
            var options = $.extend(defaults, options);
            $.pjax({
                container: options.dom,
                url: options.href,
                show: 'fade',  //展现的动画，支持默认和fade, 可以自定义动画方式，这里为自定义的function即可。
                cache: true,  //是否使用缓存
                storage: true,  //是否使用本地存储
                titleSuffix: '', //标题后缀
                filter: function (href) {
                    if (options.filter != null) {
                        options.filter(href);
                    }
                },
                fragment: options.fragment,
                timeout: 8000,
                success: function (data) {
                    var _data = data;
                }, callback: function (status) {
                    if (options.callback != null) {
                        options.callback(status);
                    } else {
                        var type = status.type;
                        switch (type) {
                            case 'success':;

                                break; //正常
                            case 'cache':;

                                break; //读取缓存 
                            case 'error':;

                                break; //发生异常
                            case 'hash':;

                                break; //只是hash变化
                        }
                    }
                }
            });

        },
        Loading: function () {
            $(document).on('pjax:send', function () {
                $web.Loading.start();
            })
            $(document).on('pjax:complete', function () {
                $web.Loading.end();
            })
        }
    },
    //加载特效
    Loading: {
        index: 0,
        //开始
        start: function () {
            $web.Loading.index = layer.load(1, { shade: [0.6, "#000"], time: 50 * 1000 }); //Lay.msg('请稍候...', { icon: 16, shade: [0.5, "#000"], time: 0 });
            return $web.Loading.index;
        },
        //结束
        end: function (i) {
            if (i) layer.close(i);
            else layer.close($web.Loading.index);
        }
    }
    , stopDefaultEvent: function (e) {//禁止默认事件
        //阻止默认浏览器动作(W3C) 
        if (e && e.preventDefault)
            e.preventDefault();
            //IE中阻止函数器默认动作的方式
        else
            window.event.returnValue = false;
        return false;
    },
    stopEventBubble: function () {//禁止事件冒泡
        var oEvent = arguments.callee.caller.arguments[0] || event;
        oEvent.cancelBubble = true;
    },


};



